package com.spider.admin.scaffold.config;

import com.spider.admin.scaffold.common.CustomAuthenticationEntryPoint;
import com.spider.admin.scaffold.common.CustomOAuth2AccessDeniedHandler;
import com.spider.admin.scaffold.common.CustomOAuth2AuthenticationEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.security.web.AuthenticationEntryPoint;

/**
 * 资源服务
 *
 * @author xiong.bo
 * @version 1.0
 * @date 2020/12/31 14:52
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Autowired
    private CustomOAuth2AccessDeniedHandler customOAuth2AccessDeniedHandler;

    @Autowired
    private CustomOAuth2AuthenticationEntryPoint customOAuth2AuthenticationEntryPoint;


    @Bean
    public AuthenticationEntryPoint authenticationEntryPoint() {
        return new CustomAuthenticationEntryPoint();
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.
            exceptionHandling()
            .and()
            .csrf().disable() //打开的csrf保护
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)//禁用session
            .and()
            .authorizeRequests()
            .antMatchers("/admin/login")
            .permitAll()
            .anyRequest()
            .authenticated()  // 开启权限认证
//                .permitAll() //permitAll代表不做权限认证
            .and()
            .exceptionHandling()
            .authenticationEntryPoint(customOAuth2AuthenticationEntryPoint) // 使用自定义的 OAuth2 入口点
            .accessDeniedHandler(customOAuth2AccessDeniedHandler); // 使用自定义的 OAuth2 拒绝处理器

    }


}
